try:
    from PIL import ImageFont, ImageDraw, Image
except ModuleNotFoundError as err:
    print("Maybe you have not installed pillow.")
    print("You may run 'pip(or pip3) install pillow' to install it.")
    print(err.msg)
    exit(-1)

import os
import sys


def Total_length(string: str) -> int:
    """计算字符串里有多少半角字符，需要注意的是某些字体比如msyh不是等宽字体，但是这个还没解决"""
    counter = string.__len__()
    for a_char in string:
        if (ord(a_char) >= 256):
            counter += 1

    return counter


def DrawWord(font_size: int, font_path: str, print_str: str, order: int):
    """给出字体取模结果"""
    font_var = ImageFont.truetype(font_path, font_size)  # 字体文件
    string_length = Total_length(print_str)  # 有多少个半角字符宽
    image_var = Image.new('RGB', (font_size // 2 * string_length, font_size),
                          (255, 255, 255))
    ImageDraw.Draw(image_var).text(xy=(0, -font_size / 16 * 4),
                                   text=print_str,
                                   font=font_var,
                                   fill=(0, 0, 0))  # 打字
    image_var.save("/tmp/zzm/image/{}.png".format(order))


if __name__ == "__main__":
    if sys.argv.__len__() < 5:
        print(sys.argv)
        print("args invalid")
        exit(1)
    # argv [1] 站名 [2] 字体 [3] 粗字体 [4] 字号
    os.system("rm -rf /tmp/zzm/image")
    os.makedirs("/tmp/zzm/image")
    station_list = open(sys.argv[1]).readlines()
    order = 0
    for station in station_list:
        order += 1
        station = station.strip()
        if station.endswith('*'):
            station = station.strip('*')
            DrawWord(int(sys.argv[4]), sys.argv[3], station, order)
        else:
            DrawWord(int(sys.argv[4]), sys.argv[2], station, order)
    # 总计数写入信息文件
    infofile = open("/tmp/zzm/image/info.txt", "w")
    infofile.write(str(order))
